#include "AttendanceRulesDialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox>
#include <QSqlQuery>
#include <QLineEdit>
#include <QTimeEdit>
#include <QFormLayout>
#include <QSpinBox>
#include <QDialogButtonBox>
#include <QDebug>
#include <QSqlError>


AttendanceRulesDialog::AttendanceRulesDialog(QWidget *parent) : QDialog(parent) {
    setWindowTitle("考勤规则设置");
   // resize(800, 600);
    // 初始化数据库连接
        if (!QSqlDatabase::database().isValid()) {
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

            if (!db.open()) {
                qCritical() << "无法打开数据库:" << db.lastError().text();
                QMessageBox::critical(nullptr, "错误", "数据库连接失败");
                return;
            }
        }
    setupUI();
    loadRules();
}

void AttendanceRulesDialog::setupUI() {
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 顶部标题和按钮
    QHBoxLayout *topLayout = new QHBoxLayout();
    QLabel *titleLabel = new QLabel("考勤规则设置");
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold;");

    addButton = new QPushButton("+ 添加规则");
    addButton->setStyleSheet("background-color: #1E90FF; color: white; padding: 5px 10px;");
    connect(addButton, &QPushButton::clicked, this, &AttendanceRulesDialog::addRule);

    delButton = new QPushButton("删除规则");
    delButton->setStyleSheet("background-color: #1E90FF; color: white; padding: 5px 10px;");
    connect(delButton, &QPushButton::clicked, this, &AttendanceRulesDialog::deleteRule);

    topLayout->addWidget(titleLabel);
    topLayout->addStretch();
    topLayout->addWidget(addButton);
    topLayout->addWidget(delButton);
    mainLayout->addLayout(topLayout);

    // 创建表格视图
    tableView = new QTableView();
    // 设置选择行为为"选择整行"
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 设置选择模式为"单选"（每次只能选择一行）
    tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    // 设置最后一列自动拉伸以填充剩余空间
    tableView->horizontalHeader()->setStretchLastSection(true);
    // 隐藏垂直表头（行号）
    tableView->verticalHeader()->hide();
    // 禁用编辑功能（用户无法直接修改表格内容）
    tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 将表格添加到布局中
    mainLayout->addWidget(tableView);

    // 分页控件
    QHBoxLayout *bottomLayout = new QHBoxLayout();
    pageInfoLabel = new QLabel();

    QPushButton *prevButton = new QPushButton("<");
    QPushButton *nextButton = new QPushButton(">");
    connect(prevButton, &QPushButton::clicked, [this](){
        if (currentPage > 1) {
            currentPage--;
            loadRules();
        }
    });
    connect(nextButton, &QPushButton::clicked, [this](){
        currentPage++;
        loadRules();
    });

    bottomLayout->addWidget(pageInfoLabel);
    bottomLayout->addStretch();
    bottomLayout->addWidget(prevButton);

    // 页码按钮
    for (int i = 1; i <= 4; i++) {
        QPushButton *pageBtn = new QPushButton(QString::number(i));
        pageBtn->setCheckable(true);
        pageBtn->setChecked(i == 1);
        pageBtn->setFixedSize(25, 25);
        connect(pageBtn, &QPushButton::clicked, [this, i](){
            currentPage = i;
            loadRules();
        });
        bottomLayout->addWidget(pageBtn);
    }

    bottomLayout->addWidget(nextButton);
    mainLayout->addLayout(bottomLayout);

    // 样式表
    setStyleSheet(R"(
        QDialog {
            background-color: #f5f5f5;
        }
        QTableView {
            background-color: white;
            border: 1px solid #ddd;
            gridline-color: #eee;
            /* 修改选中行背景颜色为较暗的蓝色 */
            selection-background-color: #ADD8E6;
        }
        QTableView QHeaderView::section {
            background-color: #f8f8f8;
            padding: 8px;
            border: none;
            border-bottom: 1px solid #ddd;
        }
        QPushButton {
            padding: 5px 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            background-color: white;
        }
        QPushButton:hover {
            background-color: #f0f0f0;
        }
        QPushButton:pressed {
            background-color: #e0e0e0;
        }
        QPushButton#addButton {
            background-color: #1E90FF;
            color: white;
            border-color: #1E90FF;
        }
        QLabel#titleLabel {
            font-size: 16px;
            font-weight: bold;
        }
    )");
}

void AttendanceRulesDialog::loadRules() {


        model = new QSqlTableModel(this);
        model->setTable("attendance_rules");
        model->setEditStrategy(QSqlTableModel::OnManualSubmit);


    // 计算分页
    int offset = (currentPage - 1) * pageSize;
   // QString limitClause = QString("1=1 LIMIT %1 OFFSET %2").arg(pageSize).arg(offset);
qDebug("// 计算分页");
    // 获取总记录数
    QSqlQuery countQuery("SELECT COUNT(*) FROM attendance_rules");
    int totalCount = 0;
    if (countQuery.next()) {
        totalCount = countQuery.value(0).toInt();
    }
 qDebug("// 获取总记录数");
    // 设置查询

 // 方法2：内存分页（性能较差）

 model->select();
 qDebug("  model->select();");
 for (int i = 0; i < model->rowCount(); ++i) {
     tableView->setRowHidden(i, i < offset || i >= offset + pageSize);
 }

    //model->setFilter(limitClause);
   // model->select();

qDebug("// 设置查询");
    // 设置表头
    model->setHeaderData(model->fieldIndex("ruleID"), Qt::Horizontal, "规则ID");
    model->setHeaderData(model->fieldIndex("department"), Qt::Horizontal, "部门");
    model->setHeaderData(model->fieldIndex("workStartTime"), Qt::Horizontal, "上班时间");
    model->setHeaderData(model->fieldIndex("workEndTime"), Qt::Horizontal, "下班时间");
qDebug("// 设置表头");
    tableView->setModel(model);

//    // 添加操作列
//    for (int i = 0; i < model->rowCount(); ++i) {
//        QPushButton *editBtn = new QPushButton("编辑");
//        QPushButton *deleteBtn = new QPushButton("删除");

//        connect(editBtn, &QPushButton::clicked, this, &AttendanceRulesDialog::editRule);
//        connect(deleteBtn, &QPushButton::clicked, this, &AttendanceRulesDialog::deleteRule);

//        QHBoxLayout *btnLayout = new QHBoxLayout();
//        btnLayout->addWidget(editBtn);
//        btnLayout->addWidget(deleteBtn);
//        btnLayout->setContentsMargins(0, 0, 0, 0);
//        btnLayout->setSpacing(5);

//        QWidget *btnWidget = new QWidget();
//        btnWidget->setLayout(btnLayout);

//        tableView->setIndexWidget(model->index(i, model->columnCount()), btnWidget);
//    }

    // 更新分页信息
    updatePagination();
}

void AttendanceRulesDialog::updatePagination() {
    QSqlQuery countQuery("SELECT COUNT(*) FROM attendance_rules");
    int totalCount = 0;
    if (countQuery.next()) {
        totalCount = countQuery.value(0).toInt();
    }

    int start = (currentPage - 1) * pageSize + 1;
    int end = currentPage * pageSize;

    pageInfoLabel->setText(QString("当前显示%1到%2条，共%3条记录")
                          .arg(start).arg(end).arg(totalCount));
}

void AttendanceRulesDialog::addRule() {
    QDialog dialog(this);
    dialog.setWindowTitle("添加考勤规则");

    QFormLayout form(&dialog);

    QLineEdit *deptEdit = new QLineEdit();
    QTimeEdit *startEdit = new QTimeEdit(QTime(9, 0));
    QTimeEdit *endEdit = new QTimeEdit(QTime(18, 0));

    form.addRow("部门:", deptEdit);
    form.addRow("上班时间:", startEdit);
    form.addRow("下班时间:", endEdit);

    QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form.addRow(&buttons);

    connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QSqlQuery query;
        query.prepare("INSERT INTO attendance_rules (department, workStartTime, workEndTime) "
                     "VALUES (?, ?, ?)");
        query.addBindValue(deptEdit->text());
        query.addBindValue(startEdit->time().toString("HH:mm"));
        query.addBindValue(endEdit->time().toString("HH:mm"));

        if (!query.exec()) {
            QMessageBox::critical(this, "错误", "添加规则失败: " + query.lastError().text());
        } else {
            loadRules();
        }
    }
}

void AttendanceRulesDialog::editRule() {
    QModelIndex index = tableView->currentIndex();
    if (!index.isValid()) return;

    int ruleID = model->data(model->index(index.row(), 0)).toInt();

    QSqlQuery query;
    query.prepare("SELECT * FROM attendance_rules WHERE ruleID = ?");
    query.addBindValue(ruleID);

    if (!query.exec() || !query.next()) {
        QMessageBox::critical(this, "错误", "获取规则信息失败");
        return;
    }

    QDialog dialog(this);
    dialog.setWindowTitle("编辑考勤规则");

    QFormLayout form(&dialog);

    QLineEdit *deptEdit = new QLineEdit(query.value("department").toString());
    QTimeEdit *startEdit = new QTimeEdit(QTime::fromString(query.value("workStartTime").toString(), "HH:mm"));
    QTimeEdit *endEdit = new QTimeEdit(QTime::fromString(query.value("workEndTime").toString(), "HH:mm"));

    form.addRow("部门:", deptEdit);
    form.addRow("上班时间:", startEdit);
    form.addRow("下班时间:", endEdit);

    QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form.addRow(&buttons);

    connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE attendance_rules SET department = ?, workStartTime = ?, "
                           "workEndTime = ? WHERE ruleID = ?");
        updateQuery.addBindValue(deptEdit->text());
        updateQuery.addBindValue(startEdit->time().toString("HH:mm"));
        updateQuery.addBindValue(endEdit->time().toString("HH:mm"));
        updateQuery.addBindValue(ruleID);

        if (!updateQuery.exec()) {
            QMessageBox::critical(this, "错误", "更新规则失败: " + updateQuery.lastError().text());
        } else {
            loadRules();
        }
    }
}

void AttendanceRulesDialog::deleteRule() {
    QModelIndex index = tableView->currentIndex();
    if (!index.isValid()) return;

    int ruleID = model->data(model->index(index.row(), 0)).toInt();
    QString department = model->data(model->index(index.row(), 1)).toString();

    if (QMessageBox::question(this, "确认删除",
                             QString("确定要删除部门[%1]的考勤规则吗?").arg(department),
                             QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        QSqlQuery query;
        query.prepare("DELETE FROM attendance_rules WHERE ruleID = ?");
        query.addBindValue(ruleID);

        if (!query.exec()) {
            QMessageBox::critical(this, "错误", "删除规则失败: " + query.lastError().text());
        } else {
            loadRules();
        }
    }
}
